import React, { useEffect, useState } from "react";
import {
  Form,
  Input,
  Upload,
  Button,
  Row,
  Col,
  TreeSelect,
  Skeleton,
} from "antd";
import { UploadOutlined } from "@ant-design/icons";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import dictionarysApi from "../../../apis/dictionarysApi";
import recursion from "../../../utils/recursion";
import suppliersApi from "../../../apis/suppliersApi";
import {
  getImagePath,
  promptResult,
  promptResult2,
} from "../../../utils/common";
import ComponentHeader from "../../../components/Page/ComponentHeader";
import { useParams } from "react-router-dom";

const SupplierEdit = () => {
  useCloseLoadingOnMount();
  const [form] = Form.useForm();
  const [manageType, setManageType] = useState([]);
  const [supplier, setSupplier] = useState({});
  const [loading, setLoading] = useState(true);
  const [loadingBtn, setLoadingBtn] = useState(false);
  const params = useParams();

  useEffect(() => {
    const fetchData = async () => {
      const res = await dictionarysApi.getDictionaryBySearchKey("manage_type");
      if (res.status >= 0) {
        recursion(res.data, "children", (tree) => {
          if (tree.children.length === 0) {
            delete tree.children;
          } else {
            tree.selectable = false;
          }
          tree.originValue = tree.value;
          tree.title = tree.value;
          tree.value = tree.id;
        });
        setManageType(res.data);
      }
      const res2 = await suppliersApi.getSuppliersDetail(params.id);
      if (res2.status >= 0) {
        setSupplier(res2.data);
      }
      setLoading(false);
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (!loading) {
      form.setFieldsValue({
        ...supplier,
        logo: supplier.logo.split(",").map((d) => {
          return {
            name: d,
            url: getImagePath(supplier.id, d),
            thumbUrl: getImagePath(supplier.id, d),
            status: "done",
          };
        }),
        photo: supplier.photo.split(",").map((d) => {
          return {
            name: d,
            url: getImagePath(supplier.id, d),
            thumbUrl: getImagePath(supplier.id, d),
            status: "done",
          };
        }),
        qualification: supplier.qualification.split(",").map((d) => {
          return {
            name: d,
            url: getImagePath(supplier.id, d),
            thumbUrl: getImagePath(supplier.id, d),
            status: "done",
          };
        }),
      });
    }
  }, [supplier]);

  const onFinish = async (values) => {
    values.retainPhoto = values.photo
      .filter((d) => d.status === "done")
      .map((d) => d.name);
    values.retainQualification = values.qualification
      .filter((d) => d.status === "done")
      .map((d) => d.name);
    values.photo = values.photo
      .filter((d) => d.status !== "done")
      .map((d) => d.originFileObj);
    values.qualification = values.qualification
      .filter((d) => d.status !== "done")
      .map((d) => d.originFileObj);
    if (values.logo[0].status === "done") {
      delete values.logo;
    } else {
      values.logo = values.logo[0].originFileObj;
    }
    const formData = new FormData();
    for (const key in values) {
      if (values[key] instanceof Array) {
        for (let i = 0; i < values[key].length; i++) {
          const v = values[key][i];
          formData.append(key, v);
        }
      } else {
        if (values[key]) formData.append(key, values[key]);
      }
    }
    formData.append("id", params.id);
    promptResult2(suppliersApi.updateSuppliers(formData), setLoadingBtn);
  };

  return (
    <>
      {loading ? (
        <Skeleton active paragraph={{ rows: 10 }} />
      ) : (
        <div className="body-container1">
          <ComponentHeader title={"供应商编辑"} marginBottom />
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            initialValues={{
              isDirectly: false,
              isShelve: true,
              isPromote: false,
              topLevel: 0,
              inventory: 0,
              photo: [],
              qualification: [],
              logo: null,
            }}
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="店铺名称"
                  name="shopName"
                  rules={[{ required: true, message: "请输入店铺名称" }]}
                >
                  <Input placeholder="请输入店铺名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="微信ID"
                  name="openId"
                  rules={[{ required: true, message: "请输入微信ID" }]}
                >
                  <Input placeholder="请输入微信ID" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="经营类别"
                  name="type"
                  rules={[{ required: true, message: "请选择经营类别" }]}
                >
                  <TreeSelect
                    treeData={manageType}
                    placeholder="请选择供应商类别"
                  ></TreeSelect>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="供应商地址"
                  name="address"
                  rules={[{ required: true, message: "请输入供应商地址" }]}
                >
                  <Input placeholder="请输入供应商地址" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="电话"
                  name="phone"
                  rules={[
                    { required: true, message: "请输入电话" },
                    { min: 11, max: 11, message: "电话号码应该为11位" },
                  ]}
                >
                  <Input placeholder="请输入电话" maxLength={11} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="企业名称"
                  name="enterpriseName"
                  rules={[{ required: true, message: "请输入企业名称" }]}
                >
                  <Input placeholder="请输入企业名称" />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item label="密码重置" name="passwordReset">
              <Input.Password placeholder="请输入重置密码" />
            </Form.Item>

            <Form.Item label="供应商公告" name="announcement">
              <Input.TextArea rows={2} placeholder="请输入供应商公告" />
            </Form.Item>

            <Form.Item
              label="企业图片"
              name="photo"
              valuePropName="fileList" // 指定值来源为组件的 fileList 属性
              getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
              rules={[{ required: true, message: "请上传企业图片" }]}
            >
              <Upload
                listType="picture"
                multiple
                maxCount={20}
                beforeUpload={() => false} // 阻止自动上传
              >
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
            </Form.Item>
            <Form.Item
              label="企业资质"
              name="qualification"
              valuePropName="fileList" // 指定值来源为组件的 fileList 属性
              getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
              rules={[{ required: true, message: "请上传企业资质" }]}
            >
              <Upload
                listType="picture"
                multiple
                maxCount={20}
                beforeUpload={() => false}
              >
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
            </Form.Item>

            <Form.Item
              label="企业logo"
              name="logo"
              valuePropName="fileList" // 指定值来源为组件的 fileList 属性
              getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
              rules={[{ required: true, message: "请上传企业logo" }]}
            >
              <Upload
                listType="picture"
                maxCount={1}
                beforeUpload={() => false}
              >
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                loading={loadingBtn}
                htmlType="submit"
                style={{ width: 120 }}
              >
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
      )}
    </>
  );
};

export default SupplierEdit;
